//
//  KABMineColCosVC.m
//  kabu
//
//  Created by XiangDongMBP on 2017/2/17.
//  Copyright © 2017年 East. All rights reserved.
//

#import "KABMineColCosVC.h"
#import "KABCosplayTCell.h"
#import <MJRefresh.h>
#import "KABModel.h"
#import "XDAFNetworking.h"
#import "ApiManager.h"
#import "MBProgressHUD+XDPrompt.h"
#import "KABCosplayDetailVC.h"
#import "GlobalHeader.h"
#import "KABHomepageVC.h"
#import <UIScrollView+EmptyDataSet.h>

@interface KABMineColCosVC ()<UITableViewDelegate, UITableViewDataSource,KABCosplayTCellDelegate, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (weak,   nonatomic) IBOutlet UITableView *tableView;
@property (strong, nonatomic) MJRefreshNormalHeader *mj_header;
@property (strong, nonatomic) MJRefreshAutoNormalFooter *mj_footer;

@property (strong, nonatomic) KABCosplayModel *cosplayList;

@end

static NSString *const kReuseCellId = @"KABCosplayTCell";
static NSInteger const kRequestCosplaySize = 20;

@implementation KABMineColCosVC

#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    [self initSubViews];
}

- (BOOL)hidesBottomBarWhenPushed {
    return YES;
}

- (void)initNavigationBar {
    NSString *topicTitle = [NSString stringWithFormat:@"#%@#", self.topicStr];
    self.navigationItem.title = (self.viewType == KABMineColCosVCTypeCollected) ? @"我的收藏" : topicTitle;
    self.navigationItem.backBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:nil action:nil];
}

- (void)initSubViews {
    UINib *nib = [UINib nibWithNibName:kReuseCellId bundle:nil];
    [self.tableView registerNib:nib forCellReuseIdentifier:kReuseCellId];
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 448.0;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    // 下拉刷新
    self.tableView.mj_header = self.mj_header;
    self.tableView.mj_footer = self.mj_footer;
    
    [self.tableView.mj_header beginRefreshing];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"空空如也" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.cosplayList.cosplay_list.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    KABCosplayTCell *cell = [tableView dequeueReusableCellWithIdentifier:kReuseCellId forIndexPath:indexPath];
    if (indexPath.section < self.cosplayList.cosplay_list.count) {
        [cell configViewWithCosplayItem:self.cosplayList.cosplay_list[indexPath.section] showDeleteBtn:NO showPullDownBtn:NO];
    }
    cell.delegate = self;
    return cell;
}

#pragma mark - UITableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 5.9;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
    detailVC.cosItem = self.cosplayList.cosplay_list[indexPath.section];
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - KABCosplayTCellDelegate
- (void)kABCosplayTCell:(KABCosplayTCell *)cell portraitImgViewTapped:(UIImageView *)imgView {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    
    KABHomepageVC *vc = [[KABHomepageVC alloc] init];
    vc.user_id = item.publisher_id;
    [self showViewController:vc sender:nil];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell praiseBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    item.is_praise = !item.is_praise;
    item.is_praise ? ++item.praise : --item.praise;
    
    // 请求服务器
    [self requestCosPraiseWithCosId:item.cosplayId isPraise:item.is_praise];
    
    // 更新界面
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell commentBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosplayDetailVC *detailVC = [[KABCosplayDetailVC alloc] init];
    detailVC.cosItem = self.cosplayList.cosplay_list[indexPath.section];
    //    detailVC.scrollToComment = YES;
    [self.navigationController pushViewController:detailVC animated:YES];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell collectBtnTapped:(UIButton *)btn {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    item.is_collected = !item.is_collected;
    
    // 请求服务器
    [self requestCosCollectWithCosId:item.cosplayId isCollected:item.is_collected];
    
    // 更新界面
    [self.tableView beginUpdates];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:indexPath.section] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
}

- (void)kABCosplayTCell:(KABCosplayTCell *)cell linkTapped:(NSURL *)url {
    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    KABCosListItem * item = self.cosplayList.cosplay_list[indexPath.section];
    
    if ([url isKindOfClass:[NSURL class]]) {
        NSInteger index = [url.absoluteString integerValue];
        NSArray *linkStrArray = item.topContentTopicAndAtUserArray;
        if (index < linkStrArray.count) {
            NSString *linkStr = linkStrArray[index];
            if (linkStr.length <= 2) {
                return;
            }
            if ([linkStr hasPrefix:@"#"]) {
                KABMineColCosVC *vc = [[KABMineColCosVC alloc] init];
                vc.viewType = KABMineColCosVCTypeTopicList;
                vc.topicStr = [linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)];
                [self showViewController:vc sender:nil];
            } else if([linkStr hasPrefix:@"@"]) {
                KABHomepageVC *vc = [[KABHomepageVC alloc] init];
                vc.user_name = [linkStr substringWithRange:NSMakeRange(1, linkStr.length - 2)];
                [self showViewController:vc sender:nil];
            }
        }
    }
}

#pragma mark - event response
#pragma mark - private methods
- (void)refreshWholeView {
    // 尾部加载更多的显示
    if (self.cosplayList.totalLoad) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        [self.tableView.mj_footer resetNoMoreData];
    }
    
    [self.tableView reloadData];
}

- (void)tableViewEndRefresh:(BOOL)isHeader {
    NSLog(@"停止刷新是否是头部---%zd", isHeader);
    if (isHeader) {
        [self.tableView.mj_header endRefreshing];
    } else {
        [self.tableView.mj_footer endRefreshing];
    }
}

- (void)tableViewRefresh:(id)sender {
    BOOL isHeader = [sender isKindOfClass:[MJRefreshHeader class]];
    if (self.viewType == KABMineColCosVCTypeCollected) {
        [self requestCosplayListWithHeader:isHeader];
    } else {
        [self requestTopicCosListWithHeader:isHeader];
    }
}

- (KABCosplayModel *)cosplayListWithDictionary:(NSDictionary *)dic isAddMore:(BOOL)AddMore {
    if ([dic[KABGlobalJsonKeyErrCode] integerValue] != 200) {
        return self.cosplayList;
    }
    
    KABCosplayModel *temp = [KABCosplayModel yy_modelWithDictionary:dic[KABGlobalJsonKeyResult]];
    if (!temp) {
        return self.cosplayList;
    }
    
    if (AddMore && self.cosplayList) {
        [self.cosplayList addMoreWithData:temp];
    } else {
        self.cosplayList = temp;
    }
    return self.cosplayList;
}

#pragma mark - network request
- (void)requestCosplayListWithHeader:(BOOL)isHeader {
    // 关注必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self tableViewEndRefresh:isHeader];
        return;
    }
    
    NSInteger startIndex = isHeader ? 0 : self.cosplayList.cosplay_list.count;

    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"index" : @(startIndex),
                           @"size" : @(kRequestCosplaySize)};
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiMineCollectCos] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self cosplayListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestTopicCosListWithHeader:(BOOL)isHeader {
    NSInteger lastId = isHeader ? 0 : self.cosplayList.cosplay_list.lastObject.cosplayId;
    NSMutableDictionary *pars = [NSMutableDictionary dictionary];
    [pars setObject:@(lastId) forKey:@"last_id"];
    [pars setObject:@(kRequestCosplaySize) forKey:@"size"];
    [pars setObject:self.topicStr forKey:@"cosplaytopic_content"];
    if ([KABModel sharedInstance].isLogin) {
        [pars setObject:@([KABModel sharedInstance].userInfo.uid) forKey:@"user_id"];
        [pars setObject:[KABModel sharedInstance].userInfo.access_token forKey:@"access_token"];
    }
    
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiTopicCosplayList] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求同一话题Cosplay列表返回：%@", responseObject);
        [self tableViewEndRefresh:isHeader];
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            [self cosplayListWithDictionary:responseObject isAddMore:!isHeader];
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求同一话题Cosplay列表失败：%@", error);
        [self tableViewEndRefresh:isHeader];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosPraiseWithCosId:(NSInteger)cosId isPraise:(BOOL)isPraise {
    // 点赞必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 点赞请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_praise" : isPraise ? @(1) : @(0)};
    NSLog(@"点赞的请求%@", pars);
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayPraise] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay点赞返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay点赞失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

- (void)requestCosCollectWithCosId:(NSInteger)cosId isCollected:(BOOL)isCollected {
    // 收藏必须要登录
    if (![KABModel sharedInstance].isLogin) {
        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        return;
    }
    
    // 收藏请求
    NSDictionary *pars = @{@"user_id" : @([KABModel sharedInstance].userInfo.uid),
                           @"access_token" : [KABModel sharedInstance].userInfo.access_token,
                           @"cosplay_id" : @(cosId),
                           @"is_collected" : isCollected ? @(1) : @(0)};
    [[XDAFNetworking sharedInstance] POST:[ApiManager apiCosplayCollected] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求Cosplay收藏返回：%@", responseObject);
        if ([responseObject[KABGlobalJsonKeyErrCode] integerValue] == 200) {
            ;
        } else {
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:responseObject[KABGlobalJsonKeyMsg]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求Cosplay收藏失败：%@", error);
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"网络请求失败"];
    }];
}

#pragma mark - getters and setters
- (MJRefreshNormalHeader *)mj_header {
    if (!_mj_header) {
        _mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_header.lastUpdatedTimeLabel.hidden = YES;
    }
    return _mj_header;
}

- (MJRefreshAutoNormalFooter *)mj_footer {
    if (!_mj_footer) {
        _mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(tableViewRefresh:)];
        _mj_footer.automaticallyRefresh = NO;
        _mj_footer.automaticallyHidden = YES;
    }
    return _mj_footer;
}

@end
